﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using Mini.Model;

namespace Mini.Common
{
    public class DownloadHelper
    {
        public static event DownloadProgressChangedEventHandler ProgressChanged;

        public static event DownloadStringCompletedEventHandler Completed;

        public static WebClient WebClientSetup()
        {
            var webClient = new WebClient
            {
                Encoding = Encoding.UTF8
            };

            webClient.DownloadStringCompleted += Completed;
            webClient.DownloadProgressChanged += ProgressChanged;
            return webClient;
        }

        public static async Task<string> DownloadString(string url)
        {
            if (string.IsNullOrEmpty(url))
                return string.Empty;

            return await WebClientSetup().DownloadStringTaskAsync(new Uri(url));

        }

        public static async Task DownloadFile(string url, string directory)
        {
            if (string.IsNullOrEmpty(url))
                return;

            await WebClientSetup().DownloadFileTaskAsync(new Uri(url), directory);
        }

        public static async Task<DownloadResult> DownloadContentWebSite(AnalysisLinkModel linkInPage, string sitePage)
        {
            var linkDownload = linkInPage.OnlineLink;
            var localLink = new DownloadResult();
            if (string.IsNullOrWhiteSpace(linkDownload))
                return localLink;

            var fileName = FileHepler.GetFileNameFromUrl(linkDownload);
            var folderFile = ConvertHelper.ConvertTagTypeToFolderTypeString(linkInPage.TagType);
            var fileDirectory = Path.Combine(sitePage, folderFile, fileName);

            await DownloadFile(linkDownload, fileDirectory);
            localLink.LocalLink = fileDirectory;
            localLink.ProjectLink = string.Format("{0}/{1}", folderFile, fileName);
            return localLink;
        }
    }
}
